package com.michael.retail.gateway.filter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.michael.retail.commons.constant.AuthConstant;
import com.nimbusds.jose.JWSObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 类功能描述:
 * <pre>
 *   全局认证 Filter
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2021/7/3 18:19
 */
@Slf4j
@Component
public final class GlobalAuthFilter implements GlobalFilter, Ordered {

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 非JWT或者JWT为空不作处理
        String token = request.getHeaders().getFirst(AuthConstant.AUTHORIZATION_KEY);

        if (!StringUtils.hasText(token) || !token.startsWith(AuthConstant.AUTHORIZATION_PREFIX)) {
            return chain.filter(exchange);
        }

        token = token.replace(AuthConstant.AUTHORIZATION_PREFIX, "");
        JWSObject jwsObject = JWSObject.parse(token);
        String payload = jwsObject.getPayload().toString();

        log.info("GlobalAuthFilter.filter() user:{}", payload);

        JSONObject jsonObject = JSONUtil.parseObj(payload);

        // 解析JWT获取jti，以jti为key判断redis的黑名单列表是否存在，存在拦截响应token失效
        //String jti = jsonObject.getStr(AuthConstant.JWT_JTI);

        // 设置用户信息到 Header 中
        request = exchange.getRequest()
                          .mutate()
                          .header(AuthConstant.JWT_PAYLOAD_KEY, payload)
                          .build();

        exchange = exchange.mutate().request(request).build();

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
